//
//  WBOAuthController.swift
//  weibobo
//
//  Created by KIMI on 16/9/21.
//  Copyright © 2016年 KIMI. All rights reserved.
//

import UIKit

class WBOAuthController: UIViewController {

    //  新浪开发平台提供的APPKey
    let WeiboAppKey = "2707543009"
    //  授权回调页
    let WeiboRedirect_Uri = "http://www.itcast.cn"
    
    //懒加载创建控件webview
    private lazy var webview: UIWebView = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()

        // 登陆请求
        requestLogin()
        setupUI()
    }

 
    //重写loadView 把webview 作为控制器的视图
    override func loadView() {
        
        //取消webView的不透明
        webview.isOpaque = false
        
        view = webview
        
        
    }
    private func requestLogin() {
        
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        //创建urlrequest对象
        let urlRequest:URLRequest = URLRequest(url: URL(string: url)!)
        
        webview.loadRequest(urlRequest)
    }
    
    private func setupUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelLogin))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", target: self, action: #selector(autoLogin))
        navigationItem.title = "微博"
    }
    
    @objc private func cancelLogin() {
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoLogin() {
        
        print("自动登陆")
        webview.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123'")
    }
}


